package com.ruoyi.adapayBalancerecharge.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.Payment;
import com.ruoyi.adapayRecord.domain.AdapayRecord;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.adapayBalancerecharge.domain.AdapayBalancerecharge;
import com.ruoyi.adapayBalancerecharge.service.IAdapayBalancerechargeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 余额支付充值记录Controller
 *
 * @author ch
 * @date 2022-03-03
 */
@RestController
@RequestMapping("/adapayBalancerecharge/adapayBalancerecharge")
public class AdapayBalancerechargeController extends BaseController
{
    @Autowired
    private IAdapayBalancerechargeService adapayBalancerechargeService;
    @Autowired
    private ISysConfigService configService;
    /**
     * 查询余额支付充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('adapayBalancerecharge:adapayBalancerecharge:list')")
    @GetMapping("/list")
    public TableDataInfo list(AdapayBalancerecharge adapayBalancerecharge)
    {
        startPage();
        List<AdapayBalancerecharge> list = adapayBalancerechargeService.selectAdapayBalancerechargeList(adapayBalancerecharge);
        return getDataTable(list);
    }

    /**
     * 导出余额支付充值记录列表
     */
    @PreAuthorize("@ss.hasPermi('adapayBalancerecharge:adapayBalancerecharge:export')")
    @Log(title = "余额支付充值记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(AdapayBalancerecharge adapayBalancerecharge)
    {
        List<AdapayBalancerecharge> list = adapayBalancerechargeService.selectAdapayBalancerechargeList(adapayBalancerecharge);
        ExcelUtil<AdapayBalancerecharge> util = new ExcelUtil<AdapayBalancerecharge>(AdapayBalancerecharge.class);
        return util.exportExcel(list, "余额支付充值记录数据");
    }

    /**
     * 获取余额支付充值记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('adapayBalancerecharge:adapayBalancerecharge:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(adapayBalancerechargeService.selectAdapayBalancerechargeById(id));
    }

    /**
     * 新增余额支付充值记录
     */
    @PreAuthorize("@ss.hasPermi('adapayBalancerecharge:adapayBalancerecharge:add')")
    @Log(title = "余额支付充值记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AdapayBalancerecharge adapayBalancerecharge)
    {
       BigDecimal money= adapayBalancerecharge.getMoney();
        if(money==null||money.compareTo(new BigDecimal(0))==0){
            return AjaxResult.error("请输入正确充值金额");
        }
        if(money.compareTo(new BigDecimal(500000))>0){
            return AjaxResult.error("单笔充值金额应小于50000");
        }
        String moneystr=money.setScale(2, RoundingMode.HALF_UP).toString();
        Map<String, Object> paymentParams = new HashMap<>();
        String app_id=configService.selectConfigByKey("adpay_app_id");
        paymentParams.put("app_id", app_id);
        String order_no="alipay_qr" + System.currentTimeMillis();
        paymentParams.put("order_no", order_no);
        paymentParams.put("pay_channel", "alipay_qr");
        paymentParams.put("pay_amt", moneystr);

        paymentParams.put("goods_title", "充值");
        paymentParams.put("goods_desc", "充值");
        List<Map<String, String>> memberList = new ArrayList<>();
        Map<String, String> divMember = new HashMap<>();
        divMember.put("member_id", "0");//分账用户 Member对象 的 id；若是商户本身时，传入0
        divMember.put("amount", moneystr);//分账金额，精确到分
        memberList.add(divMember);
        paymentParams.put("div_members", memberList);
        paymentParams.put("fee_mode", "O");
//        paymentParams.put("pay_mode", "");
//        Map<String, Object> expendParams = new HashMap<>();
//        expendParams.put("open_id", openId);
//        paymentParams.put("expend", expendParams);
        String domain=configService.selectConfigByKey("domain");
        String notify_url=/*request.getScheme()+*/domain+"/prod-api/client/adapayBalancerecharge/notify";
        paymentParams.put("notify_url", notify_url);
        Map<String, Object> payment = new HashMap<>();
        AdapayBalancerecharge adapayBalancerechargeNew=new AdapayBalancerecharge();
        adapayBalancerechargeNew.setOrderNo(order_no);
        adapayBalancerechargeNew.setReqState(DicConstants.SYS_Y.getCode());
        adapayBalancerechargeNew.setReqParam(paymentParams.toString());
        adapayBalancerechargeNew.setMoney(money);
        try {

            payment = Payment.create(paymentParams);
        } catch (BaseAdaPayException e) {
            e.printStackTrace();
            adapayBalancerechargeNew.setReqState((DicConstants.SYS_N.getCode()));
            adapayBalancerechargeNew.setReqFailMsg(e.getMessage());
            adapayBalancerechargeService.insertAdapayBalancerecharge(adapayBalancerechargeNew);
            return AjaxResult.error(e.getMessage());
        }
        adapayBalancerechargeNew.setResParam(payment.toString());
        String error_code = (String) payment.get("error_code");
        if (null != error_code) {

            String error_msg = (String) payment.get("error_msg");
            System.out.println("error_code:" + error_code + "............." + error_msg);
            adapayBalancerechargeNew.setReqState((DicConstants.SYS_N.getCode()));
            adapayBalancerechargeNew.setReqFailMsg(error_msg);
            adapayBalancerechargeService.insertAdapayBalancerecharge(adapayBalancerechargeNew);
            return AjaxResult.error(error_msg);
        }

        adapayBalancerechargeNew.setPaymentId( (String)payment.get("id"));
        adapayBalancerechargeService.insertAdapayBalancerecharge(adapayBalancerechargeNew);



        return AjaxResult.success();
    }

    /**
     * 修改余额支付充值记录
     */
    @PreAuthorize("@ss.hasPermi('adapayBalancerecharge:adapayBalancerecharge:edit')")
    @Log(title = "余额支付充值记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AdapayBalancerecharge adapayBalancerecharge)
    {
        adapayBalancerecharge.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(adapayBalancerechargeService.updateAdapayBalancerecharge(adapayBalancerecharge));
    }

    /**
     * 删除余额支付充值记录
     */
    @PreAuthorize("@ss.hasPermi('adapayBalancerecharge:adapayBalancerecharge:remove')")
    @Log(title = "余额支付充值记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(adapayBalancerechargeService.logicDeleteAdapayBalancerecharge(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }
}
